package cn.edu.swu.book;

import java.sql.*;
import java.util.Properties;

public class DatabaseUtils {
    private static final String URL = "jdbc:mysql://localhost:3306/bookstore";
    private static final String USER = "root"; // 数据库用户名
    private static final String PASSWORD = "s15095609043l@zy_Yao-yao"; // 数据库密码

    public static Connection getConnection() throws SQLException {
        Properties connectionProps = new Properties();
        connectionProps.put("user", USER);
        connectionProps.put("password", PASSWORD);
        return DriverManager.getConnection(URL, connectionProps);
    }

    public static Book getBookDetailsFromId(int bookId) throws SQLException {
        String sql = "SELECT * FROM book WHERE id = ?";
        try (Connection connection = getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

            statement.setInt(1, bookId);
            ResultSet resultSet = statement.executeQuery();

            if (resultSet.next()) {
                return new Book(
                        resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getString("author"),
                        resultSet.getDouble("price"),
                        resultSet.getString("memo"),
                        resultSet.getDate("publish"),
                        resultSet.getString("image")
                );
            }
        }
        return null; // 如果没有找到书籍，返回null
    }

}
